package application

import (
	"context"
	"github.com/edgexfoundry/edgex-go/internal/app/core/metadata/container"
	"github.com/edgexfoundry/edgex-go/internal/app/models"
	"github.com/edgexfoundry/edgex-go/internal/pkg/correlation"
	bootstrapContainer "github.com/edgexfoundry/go-mod-bootstrap/v2/bootstrap/container"
	"github.com/edgexfoundry/go-mod-bootstrap/v2/di"
	"github.com/edgexfoundry/go-mod-core-contracts/v2/errors"
)

func DeviceCommandAdd(deviceId string, d models.DeviceCommand, ctx context.Context, dic *di.Container) errors.EdgeX {
	dbClient := container.DBClientFrom(dic.Get)
	lc := bootstrapContainer.LoggingClientFrom(dic.Get)

	_, err := dbClient.DeviceCommandAdd(deviceId, d)
	if err != nil {
		return errors.NewCommonEdgeXWrapper(err)
	}

	lc.Debugf("DeviceProfile deviceCommands added on DB successfully. Correlation-id: %s ", correlation.FromContext(ctx))
	go SyncDeviceProfileById(deviceId, ctx, dic)
	return nil
}

func DeviceCommandGet(deviceId string, offset, limit int, ctx context.Context, dic *di.Container) ([]models.DeviceCommand, uint32, errors.EdgeX) {
	dbClient := container.DBClientFrom(dic.Get)
	lc := bootstrapContainer.LoggingClientFrom(dic.Get)

	commands, totalCount, err := dbClient.DeviceCommandGet(deviceId, offset, limit)
	if err != nil {
		return nil, 0, errors.NewCommonEdgeXWrapper(err)
	}

	lc.Debugf("DeviceProfile deviceCommands added on DB successfully. Correlation-id: %s ", correlation.FromContext(ctx))
	return commands, totalCount, nil
}

func DeviceCommandDelete(deviceId, commandId string, ctx context.Context, dic *di.Container) errors.EdgeX {
	dbClient := container.DBClientFrom(dic.Get)
	lc := bootstrapContainer.LoggingClientFrom(dic.Get)

	err := dbClient.DeviceCommandDelete(deviceId, commandId)
	if err != nil {
		return errors.NewCommonEdgeXWrapper(err)
	}

	lc.Debugf("DeviceProfile deviceCommands added on DB successfully. Correlation-id: %s ", correlation.FromContext(ctx))
	go SyncDeviceProfileById(deviceId, ctx, dic)
	return nil
}

func DeviceCommandUpdate(deviceId string, d models.DeviceCommand, ctx context.Context, dic *di.Container) errors.EdgeX {
	dbClient := container.DBClientFrom(dic.Get)
	lc := bootstrapContainer.LoggingClientFrom(dic.Get)

	err := dbClient.DeviceCommandUpdate(deviceId, d)
	if err != nil {
		return errors.NewCommonEdgeXWrapper(err)
	}

	lc.Debugf("DeviceProfile deviceCommands added on DB successfully. Correlation-id: %s ", correlation.FromContext(ctx))
	go SyncDeviceProfileById(deviceId, ctx, dic)
	return nil
}
